package store.lunangangster.nodeflow.parser.el.operator;

import com.ql.util.express.Operator;
import store.lunangangster.nodeflow.core.component.ExitComponent;
import store.lunangangster.nodeflow.exception.RuleSourceParseException;
import store.lunangangster.nodeflow.parser.el.OperatorHelper;
import store.lunangangster.nodeflow.rt.element.Node;
import store.lunangangster.nodeflow.rt.element.flow.LoopFlow;
import store.lunangangster.nodeflow.util.Converter;

/**
 * 用于扩展LoopFlow的EXIT操作符
 *
 * @author cwk
 * @version 1.0
 */
public class ExitOperator extends Operator {

  @Override
  public Object executeInner(Object[] list) throws RuleSourceParseException {
    OperatorHelper.checkArguments(list);

    if (list.length != 2) {
      throw new RuleSourceParseException("Incompatible executable for EXIT: should be like FOR(forNode).EXIT(exitNode) or FOR(forNode).DO(flow).EXIT(exitNode)");
    }
    LoopFlow loopFlow = Converter.convert(list[0], LoopFlow.class);
    if (loopFlow.getExitNode() != null) {
      throw new RuleSourceParseException("Incompatible executable for LoopFlow: LoopFlow already has exitNode, cannot use EXIT() again");
    }
    Node exitNode = Converter.convert(list[1], Node.class);
    if (!exitNode.isComponent(ExitComponent.class)) {
      throw new RuleSourceParseException("Incompatible executable for EXIT: should be like FOR(forNode).EXIT(exitNode) or FOR(forNode).DO(flow).EXIT(exitNode)");
    }
    loopFlow.setExitNode(exitNode);
    return loopFlow;
  }
}
